namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using SimpleWebServices.Models;
    using SimpleWebServices.Web.Routing;

    [InternalServerError]
    [Allow(Methods = "GET, HEAD, OPTIONS, POST")]
    [CacheControl, ContentLanguage, ContentLocation, ContentMD5]
    public sealed class TenantFormController : TenantController, IRegisterRoutes
    {
        public void Register(RouteCollection routes)
        {
            if (null == routes)
            {
                throw new ArgumentNullException("routes");
            }

            routes.Add(new TenantRoute<TenantForm>(this.GetType(), "form"));
        }

        [ContentNegotiation(".html", "*/*, text/*, text/html")]
        public ActionResult HtmlRepresentation(CultureInfo language)
        {
            return this.HtmlView(language, new TenantForm().Populated<TenantForm>().ApplyDefaultValues<TenantForm>());
        }

        [ContentNegotiation(".xhtml", "application/xhtml+xml")]
        public ActionResult XhtmlRepresentation(CultureInfo language)
        {
            return this.XhtmlView(language, new TenantForm().Populated<TenantForm>().ApplyDefaultValues<TenantForm>());
        }

        [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "The derived type is necessary.")]
        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "ASP.NET MVC requires the method to be an instance member.")]
        [Post]
        public ActionResult Post(TenantForm model)
        {
            if (null == model)
            {
                throw new ArgumentNullException("model");
            }

            HttpRequestBase request = HttpContextFactory.Current.Request;

            string location = null;
            if (null != model.Results && model.Results.Token.HasValue)
            {
                location = string.Concat(request.Path.Replace("/form", "/submission"), request.RawQueryString(model.Results.Token));
            }
            else
            {
                location = string.Concat(request.Path, request.RawQueryString(model.Token));
            }

            return new SeeOtherResult(location);
        }
    }
}